<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>15.数值类型转换技巧与NaN类型</title>
</head>

<body>
  <input type="text" value="66" name="num">
  <script>
    // NaN not a number
    console.log(Number("houdunren")); //NaN
    console.log(2 / 'houdunren'); //NaN
    //NaN不能使用 == 比较 ,可以用Number.isNaN() ，Object.is() 比较
    var res = 2 / 'houdunren';
    if (Number.isNaN(res)) {
      console.log('Error');
    }
    var res = 2 / 'houdunren';
    console.log(Object.is(res, NaN));

    // 类型转换 基本上可以转换所有类型
    console.log(Number('houdunren')); //NaN
    console.log(Number(true));	//1
    console.log(Number(false));	//0
    console.log(Number('9'));	//9
    console.log(Number([]));	//0
    console.log(Number([5]));	//5
    console.log(Number([5, 2]));	//NaN
    console.log(Number({}));	//NaN
    console.log(Number({ 
      valueOf: function () { 
        return 991; 
      } 
    }));	//991

    //使用乘法进行隐式类型转换
    let num = document.querySelector("[name = 'num']").value;
    console.log(num + 5); //665
    console.log(num * 1 + 5); //71

    //提取字符串开始去除空白后的数字转为整数。
    console.log(parseInt('  99houdunren'));	//99
    console.log(parseInt('18.55'));	//18
    //提取字符串开始去除空白后的数字转为浮点数。
    console.log(parseFloat('  99houdunren'));	//99
    console.log(parseFloat('18.55'));	//18.55
    //使用 toFixed 可对数值舍入操作，参数指定保存的小数位
    console.log(1.556.toFixed(2)); //1.56
  </script>
</body>

</html>